package com.gwd.task.untils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhiyongming
 * @date 2020/11/11 17:17
 */
@Component
public class JwtUtil {
    // 过期时间为1小时
    private static final long EXPIRE_TIME = 60 * 60 * 2000;
    // token私钥
    private static final String TOKEN_SECRET = "BigMing";

    private static final Map<Long, String> kv = new HashMap<>();
    /**
     * 生成签名，1小时后过期
     * @param username 用户名
     * @param id 用户id
     * @return String
     */
    public static String sign(String username, Long id) {
        // 过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        // 私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        // 设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        // 附带username和userId生成签名
        String token = JWT.create().withHeader(header).withClaim("username", username)
                .withClaim("userId", id).withExpiresAt(date).sign(algorithm);
        putMap(token, id);
        return token;
    }

    /**
     * token校验
     */
    public static Long verity(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            Map<String, Claim> claims = verifier.verify(token).getClaims();
            return verityMap(Long.valueOf(claims.get("userId").asInt()), token);
        } catch (IllegalArgumentException | JWTVerificationException e) {
            return 0L;
        }
    }

    /**
     * 新生成的token添加到map中
     */
    public static void putMap(String token, Long userId) {
        String s = kv.get(userId);
        if (s!=null) {
            kv.remove(userId);
        }
        kv.put(userId, token);
    }

    /**
     * 登出移除某个key
     */
    public static void removeMap(Long userId) {
        kv.remove(userId);
    }

    /**
     * 校验传入的token是否在map中
     */
    public static Long verityMap(Long userId, String token) {
        String s = kv.get(userId);
        if (s==null) {
            return 0L;
        }
        return s.equals(token)?userId:0L;
    }

}